package org.summer.netty;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class TestJdkFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        DefaultPromise<String> promise = new DefaultPromise<>(new NioEventLoopGroup().next());

        new Thread(()->{
            try {
                log.info("waiting ...");
                TimeUnit.SECONDS.sleep(1);
                promise.setSuccess("mk");
            } catch (InterruptedException e) {
                promise.setFailure(e);
            }
        }).start();

        log.info("waiting ...");
        log.info("result -> [{}]", promise.get());
    }

    private static void nettyFutureTest() {
        NioEventLoopGroup executors = new NioEventLoopGroup();

        io.netty.util.concurrent.Future<String> future = executors.next().submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("do something");
                TimeUnit.SECONDS.sleep(1);
                return "mk";
            }
        });

        future.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super String>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super String> future) throws Exception {
                log.info("result -> [{}]", future.get());
                executors.shutdownGracefully();
            }
        });
    }

    private static void testJdkFuture() throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(2);

        Future<String> future = service.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("do something");
                TimeUnit.SECONDS.sleep(1);
                return "mk";
            }
        });

        log.info(future.get());

        service.shutdown();
    }
}
